package com.song.elasticsearch.controller;

import com.alibaba.fastjson.JSONObject;
import com.song.elasticsearch.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Api(tags = {"Elasticsearch测试控制器"})
@RestController
public class ElasticsearchController {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @ApiOperation(value = "测试查询")
    @GetMapping("/query")
    public Object query(String name) throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        if(ObjectUtils.isNotEmpty(name)){
            queryBuilder.must(QueryBuilders.wildcardQuery("name", "*" + name + "*"));
        }
        builder.query(queryBuilder);
        SearchRequest searchRequest = new SearchRequest("test-user").source(builder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        List<User> records = new ArrayList<>();
        for (SearchHit hit : hits) {
            User user = JSONObject.parseObject(hit.getSourceAsString(), User.class);
            records.add(user);
        }
        return JSONObject.toJSONString(records);
    }
}
